package com.gxar.quick.ar.server.base.controller;

import com.alibaba.fastjson2.JSONObject;
import com.gxar.common.entity.Result;
import com.gxar.common.utils.DingNoticeUtils;
import com.gxar.quick.ar.server.base.model.pay.info.WechatPrepayAttachInfo;
import com.gxar.quick.ar.server.base.reference.UserReference;
import com.gxar.quick.ar.server.base.sdk.IdentifySDK;
import com.gxar.quick.ar.server.db.mapper.WorksMapper;
import com.gxar.quick.ar.server.db.model.TestEntity;
import com.gxar.quick.ar.server.db.repository.TestRepository;
import com.gxar.quick.ar.server.db.service.ExchangeItemService;
import com.gxar.quick.ar.server.db.service.WorksService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 坑位接口
 *
 * @author linsy
 * @version 1.0
 * @created 2023/11/3 15:44
 */
@Api(tags = "测试接口")
@RestController
@RequestMapping("/api/test")
@RequiredArgsConstructor
@Slf4j
public class TestController {

//    private final QiMenProperties qiMenProperties;

    //    private final BaiduTranslateSDK translateSdk;
    private final IdentifySDK identifySdk;
    private final WorksMapper worksMapper;
    private final WorksService worksService;
    private final TestRepository testRepository;
    private final UserReference userReference;
    private final ExchangeItemService exchangeItemService;

    @GetMapping("/sleep")
    public Result<String> sleep() throws InterruptedException {
        log.info("进入");
//        Thread.sleep(15000L);
        return Result.success("成功");
    }

    @PostMapping("/paySuccess/{order_id}")
    public Result<Boolean> paySuccess(@PathVariable("order_id") Long orderId, @RequestBody WechatPrepayAttachInfo attachInfo) {
        exchangeItemService.exchangeITemPaySuccess(orderId, attachInfo);
        return Result.success("支付成功", true);
    }

//    @PostMapping("/url-link")
//    public Result<String> urlLink(@RequestBody UrlLinkVO urlLinkVo) {
//        String urlLink = WechatAppSDK.generateUrlLink(WechatPayConstant.GOODS_PLUS_APP_ID, WechatPayConstant.GOODS_PLUS_APP_SECRET, urlLinkVo);
//        return Result.success("操作成功", urlLink);
//    }

//    @PostMapping("/qr-code")
//    public Result<String> qrCode(@RequestBody QrCodeVO qrCodeVo) {
//        String urlLink = WechatAppSDK.generateQrCode(WechatPayConstant.APP_ID, WechatPayConstant.APP_SECRET, qrCodeVo);
//        return Result.success("操作成功", urlLink);
//    }
//
//    @GetMapping("/lottery")
//    public Result<com.alibaba.fastjson.JSONObject> lottery(@RequestParam("token") String token, @RequestParam("id") String id) {
//        String url = qiMenProperties.getUrl();
//        com.alibaba.fastjson.JSONObject lottery = QiMenSDK.lottery(url + "/award/lottery", token, id);
//        return Result.success(lottery);
//
//    }

//    @GetMapping("/users")
//    public Result<List<UserProfile>> batchUser() {
//        List<Long> userId = new ArrayList<>();
//        userId.add(169L);
//        userId.add(208L);
//        List<UserProfile> userProfiles = userReference.batchProfileByAuthorize(userId, null, null);
//        return Result.success(userProfiles);
//    }
//
    @ApiOperation("批量添加识别图")
    @GetMapping("/batch-add-identify")
    public Result<String> historyIdentify() {
        StringBuilder res = new StringBuilder();
        List<TestEntity> testEntityList = testRepository.findAll();
        for (TestEntity jsonObject : testEntityList.stream().sorted(Comparator.comparing(TestEntity::getUserId)).collect(Collectors.toList())) {
            Long id = jsonObject.getId();
            Long userId = jsonObject.getUserId();
            String identify = jsonObject.getIdentify();
            JSONObject identifyObject = JSONObject.parseObject(identify, JSONObject.class);
            String linkUrl = identifyObject.getString("linkUrl");
            System.out.println("作品id:" + id + " 用户ID:" + userId + " 图片地址：" + linkUrl);
            try {
                String addIdentify = identifySdk.addIdentify(userId, id, linkUrl);
                if (StringUtils.isNotBlank(addIdentify)) {
                    String error = "识别图上传失败：" + "作品id:" + id + " 用户ID:" + userId + " 图片地址：" + linkUrl + "原因：" + addIdentify;
                    res.append(error).append("\n");
                }
            } catch (Exception e) {
                String error = "识别图上传失败：" + "作品id:" + id + " 用户ID:" + userId + " 图片地址：" + linkUrl + "原因：" + e.getMessage();
                res.append(error).append("\n");
            }
        }
        System.out.println("上传完成");
        System.out.println("失败：" + res);
        return Result.success();
    }
//
//    @ApiOperation("添加识别图")
//    @GetMapping("/add-identify")
//    public Result<String> addIdentify(@RequestParam("user_id") Long userId, @RequestParam("work_id") Long workId, @RequestParam("image") String image) {
//        StringBuilder msg = new StringBuilder();
//        try {
//            String result = identifySdk.addIdentify(userId, workId, image, "GoodsAR");
//            if (com.gxar.common.utils.StringUtils.isNotBlank(result)) {
//                msg.append("批量测试").append("，上传云识别图失败。").append("\n");
//                msg.append("原因：").append(result).append("\n");
//                msg.append("用户ID：").append(userId).append("\n");
//                msg.append("作品ID：").append(workId).append("\n");
//                msg.append("识别图：").append(image);
//            }
//        } catch (Exception e) {
//            msg.append("批量测试").append("， 上传云识别图失败。").append("\n");
//            msg.append("原因：").append(e.getMessage()).append("\n");
//            msg.append("用户ID：").append(userId).append("\n");
//            msg.append("作品ID：").append(workId).append("\n");
//            msg.append("识别图：").append(image);
//        }
//        if (com.gxar.common.utils.StringUtils.isNotBlank(msg.toString())) {
//            DingNoticeUtils.sendDingWarningMsg(msg.toString(), "https://oapi.dingtalk.com/robot/send?access_token=b1fac6703e53d1acc806760ff57a8d27b373211e91383316e8800e4e729adffd", "SECb185cc37d1c77597ceca93ed5058cdcf2d7a9a405a6da2a6941ac4027884a896");
//        }
//        return Result.success("identify");
//    }

//    @ApiOperation("识别图识别")
//    @GetMapping("/predict-identify")
//    public Result<String> predictIdentify(@RequestParam("user_id") Long userId, @RequestParam("work_id") Long workId, @RequestParam("image") String image) {
//        StringBuilder msg = new StringBuilder();
//        try {
//            String result = identifySdk.predictIdentify(userId, workId, image, multiResult);
//            log.info("识别结果：{}", result);
//        } catch (Exception e) {
//            msg.append("批量测试").append("， 上传云识别图失败。").append("\n");
//            msg.append("原因：").append(e.getMessage()).append("\n");
//            msg.append("用户ID：").append(userId).append("\n");
//            msg.append("作品ID：").append(workId).append("\n");
//            msg.append("识别图：").append(image);
//        }
//        if (com.gxar.common.utils.StringUtils.isNotBlank(msg.toString())) {
//            DingNoticeUtils.sendDingWarningMsg(msg.toString(), "https://oapi.dingtalk.com/robot/send?access_token=b1fac6703e53d1acc806760ff57a8d27b373211e91383316e8800e4e729adffd", "SECb185cc37d1c77597ceca93ed5058cdcf2d7a9a405a6da2a6941ac4027884a896");
//        }
//        return Result.success("identify");
//    }
//
//    @ApiOperation("删除识别图")
//    @GetMapping("/del-identify")
//    public Result<String> delIdentify(@RequestParam("work_id") Long workId, @RequestParam("image") String image) {
//        UserProfile userProfile = LoginUserThread.get();
//        String identify = identifySdk.delIdentify(userProfile.getId(), workId, image);
//        return Result.success(identify);
//    }

//    @GetMapping("/translate")
//    public Result<String> translate(@RequestParam("src") String src) {
//        String result = translateSdk.autoTranslateEn(src);
//        return Result.success(result);
//    }

    private String getIdentifyUrl(String identify) {
        if (StringUtils.isBlank(identify)) {
            return null;
        }
        JSONObject newIdentifyObject = JSONObject.parseObject(identify);
        if (newIdentifyObject != null) {
            return newIdentifyObject.getString("linkUrl");
        }
        return null;
    }

}
